You write custom CUDA kernels to replace the PyTorch operators in the given EvoNorm architecture to get speedups.
You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining normalization+affine_transform+nonlinear_gating), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.

Technologies Used :

PyTorch: Deep learning framework

CUDA: GPU acceleration for parallel computing

C++/CUDA C++: High-performance kernel programming

Inline C++/CUDA Extension (torch.utils.cpp_extension.load_inline): Just-In-Time (JIT) compilation of custom operators

Hellinger Distance: Statistical measure for similarity between probability distributions

Vectorized Memory Access (float4): Uses 128-bit wide loads (4 floats) to improve memory bandwidth utilization

Instruction-Level Parallelism (ILP): Processes multiple float4 elements per loop iteration to hide instruction latency

Warp-Level Primitives: Uses __shfl_down_sync for efficient intra-warp reduction

Two-Stage Parallel Reduction: Combines warp-level reduction with shared memory and block-level reduction

Grid-Stride Loops with Boundary Checks: Handles data of arbitrary size safely

Constant Memory/__ldg: Uses read-only data cache for improved memory access patterns

Atomic Operations (atomicAdd): Safely accumulates results from multiple thread blocks

Multi-Kernel Launch Configuration: Dynamically calculates grid dimensions based on GPU SM count and data size

Fast Math Operations: Uses sqrtf with --use_fast_math compiler flag

Memory Coalescing: Optimized memory access patterns through contiguous tensor layout

Tensor Contiguity Enforcement: Ensures optimal memory layout in PyTorch wrapper

Mathematical Optimization: Pre-computes scaling factor (0.70710678 = 1/√2) for final normalization

Numerical Stability: Adds epsilon (eps) to prevent numerical underflow in square root operations

Pointer Chasing Loop: Efficient main loop with ILP-unrolled memory access patterns

Tail Processing: Handles remaining elements after main vectorized loop

Semi-Synchronous Reduction: Reduces atomic operation overhead through warp-level aggregation

Device Query API: Uses cudaGetDevice and cudaDeviceGetAttribute for optimal kernel configuration


Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
import torch
import torch.nn as nn
import torch.nn.functional as F

N, C, H, W = 32, 64, 56, 56
EPS = 1e-6


class HellingerDistance(nn.Module):

    def __init__(self, eps=1e-6):
        super().__init__()
        self.eps = eps

    def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
        x = torch.relu(x)
        y = torch.relu(y)

        sqrt_x = torch.sqrt(x + self.eps)
        sqrt_y = torch.sqrt(y + self.eps)

        diff_sq = torch.square(sqrt_x - sqrt_y)

        sum_sq = torch.sum(diff_sq, dim=[1, 2, 3])

        return torch.sqrt(sum_sq + self.eps) / 1.41421356  # 1/sqrt(2)


class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.op = HellingerDistance(EPS)

    def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
        return self.op(x, y)


def get_inputs():
    x = torch.rand(N, C, H, W, dtype=torch.float32)
    y = torch.rand(N, C, H, W, dtype=torch.float32)
    return [x, y]


def get_init_inputs():
    return []